package co.fitstart.admin.web.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.AbstractView;

import com.demo2do.core.utils.StringUtils;

public class DownloadTemplateView extends AbstractView {
    
    private static final String CONTENT_TYPE = "text/plain";
    
    private static final String CONTENT_DISPOSITION_PREFIX = "attachment;";
    
    private static final String DEFAULT_FILE_NAME = "download.txt";
    
    private String fileName;
    
    private String path;
    
    //private static final Log logger = LogFactory.getLog(DownloadTemplateView.class);
    
    /**
     * @param fileName
     * @param path
     */
    public DownloadTemplateView(String fileName, String path) {
        this.fileName = fileName;
        this.path = path;
        super.setContentType(CONTENT_TYPE);
    }
    
    /**
     * @return the fileName
     */
    public String getFileName() {
        return fileName;
    }

    /**
     * @param fileName the fileName to set
     */
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    
    /**
     * 
     * @return
     */
    public String getContentDisposition() {
        String fileName = StringUtils.isBlank(this.fileName) ? DEFAULT_FILE_NAME : this.fileName;
        return CONTENT_DISPOSITION_PREFIX + " filename=" + fileName;
    }


    /*
     * (non-Javadoc)
     * @see org.springframework.web.servlet.view.AbstractView#renderMergedOutputModel(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
        
        
        File file = new File(this.path + this.fileName);
        FileInputStream inputStream = new FileInputStream(file);
        
        response.setHeader("Content-Disposition", getContentDisposition());
        // no cache here
        
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
        response.setDateHeader("Expire", 0);
        response.setContentType(super.getContentType());
        
        OutputStream outputStream = response.getOutputStream();
        
        int buffer;
        while((buffer = inputStream.read())!= -1)
        {
            outputStream.write(buffer);
        }
        
        inputStream.close();
        outputStream.close();
        outputStream.flush();
    }

}
